using Microsoft.EntityFrameworkCore;
using UwinEducation.Domain.Entities;
using UwinEducation.Domain.IRepositories;
using UwinEducation.Infrastructure.Persistence;

using UwinEducation.Shared.Models;

namespace UwinEducation.Infrastructure.Repositories
{
    public class ClassroomRepository : Repository<Classroom, Guid>, IClassroomRepository
    {
        public ClassroomRepository(ApplicationDbContext context) : base(context)
        {
        }

        public async Task<PagedResult<Classroom>> GetPagedListAsync(ClassroomPageRequest pageRequest)
        {
            var query = _context.Classrooms.AsQueryable();

            // 如果有搜索条件，添加过滤
            //if (!string.IsNullOrEmpty(pageRequest.Search))
            //{
            //    query = query.Where(r => r.Name.Contains(pageRequest.Search));
            //}
            if (!string.IsNullOrEmpty(pageRequest.Name))
            {
                query = query.Where(r => r.Name.Contains(pageRequest.Name));
            }
            if (!string.IsNullOrEmpty(pageRequest.Remarks))
            {
                query = query.Where(r => r.Remarks.Contains(pageRequest.Remarks));
            }

            var total = await query.CountAsync();
            
            // 先获取所有数据，然后在内存中进行自然排序
            var items = await query.ToListAsync();
            
            // 按照教室名称的自然排序（考虑数字部分）
            items = items
                .Select(r => new 
                {
                    Classroom = r,
                    Prefix = new string(r.Name.TakeWhile(c => !char.IsDigit(c)).ToArray()),
                    Number = int.TryParse(new string(r.Name.Replace("1 Spring St ","").SkipWhile(c => !char.IsDigit(c)).TakeWhile(c => char.IsDigit(c)).ToArray()), out int num) ? num : 0
                })
                .OrderBy(x => x.Prefix)
                .ThenBy(x => x.Number)
                .Select(x => x.Classroom)
                .Skip((pageRequest.PageIndex - 1) * pageRequest.PageSize)
                .Take(pageRequest.PageSize)
                .ToList();

            return new PagedResult<Classroom>
            {
                Total = total,
                Items = items
            };
        }

        public async Task<Classroom> GetDetailsByIdAsync(Guid id)
        {
            return await _context.Classrooms
                .FirstOrDefaultAsync(c => c.Id == id);
        }

        public async Task<bool> ExistsByNameAsync(string name, Guid? excludeId = null)
        {
            return await _context.Classrooms
                .Where(c => c.Name == name && (!excludeId.HasValue || c.Id != excludeId.Value))
                .AnyAsync();
        }
    }
} 